﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using NCrawler.HtmlProcessor.Extensions;
using NCrawler.Extensions;

namespace ZCrawler
{
    public class ZRuleNav : ZBasicRule
    {
        private List<string> links;
        public ZRuleNav(string fn):base(fn)
        {
            links = new List<string>();
        }
        public ZRuleNav():base()
        {
            links = new List<string>();
        }
        public override string Process(HtmlAgilityPack.HtmlDocument doc)
        {
            if(this.links.Count > 0)
            {
                if (EOF)
                    return "";
                string result = this.links[tag];
                processors.ForEach(p =>
                {
                    result = p.Process(result);
                });
                tag++;
                EOF = tag == this.links.Count;
                return result;
            }
            DocumentWithLinks links = doc.GetLinks();
            List<string> totalLinks = links.Links.Union(links.References).ToList();
            try
            {
                List<string> matchedLinks = totalLinks.Where((k) =>
                    {
                        if(!k.IsNullOrEmpty())
                        {
                            return k.IndexOf(navMark) != -1; 
                        }
                        else return false;
                    }).ToList();
                EOF = matchedLinks.Count == 0;
                if(!EOF)
                {
                    this.links = matchedLinks;
                    string result = this.links[tag];
                    processors.ForEach(p =>
                        {
                            result = p.Process(result);
                        });
                    tag++;
                    
                    return result;
                }
                else
                {
                    return "";
                }
            }
            catch(Exception)
            {
                EOF = true;
                return "";
            }
        }

        public override void reset()
        {
            base.reset();
            links.Clear();
        }

        public override string Description()
        {
            return navMark;
        }
    }
}
